// src/main/java/com/easy/util/CaptchaUtil.java
package com.easy.util;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;

import java.util.Base64;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public class CaptchaUtil {

    // 存储 key->验证码 映射
    private static final Map<String, String> CAPTCHA_STORE = new ConcurrentHashMap<>();

    /**
     * 生成验证码
     * @return JSON 响应，code=200 表示成功
     */
    public static Map<String, Object> getCaptcha() {
        try {
            // 定义验证码字符集，避免易混淆字符
            RandomGenerator randomGenerator = new RandomGenerator("ABCDEFGHJKMNPQRSTUVWXYZ23456789", 4);
            // 宽200，高100，字符数4，干扰线3
            LineCaptcha lineCaptcha = new LineCaptcha(200, 100, 4, 3);
            lineCaptcha.setGenerator(randomGenerator);
            lineCaptcha.createCode();

            // 使用标准Base64编码而不是URL安全的编码
            String imgBase64 = Base64.getEncoder().encodeToString(lineCaptcha.getImageBytes());

            // 生成唯一 key
            String key = UUID.randomUUID().toString();
            CAPTCHA_STORE.put(key, lineCaptcha.getCode());

            System.out.println("验证码 key: " + key + ", code: " + lineCaptcha.getCode());

            // 返回与前端期望一致的数据结构
            return Map.of(
                    "code", 200,
                    "data", Map.of(
                            "key", key,
                            "base64", imgBase64
                    )
            );
        } catch (Exception e) {
            e.printStackTrace();
            return Map.of(
                    "code", 500,
                    "msg", "验证码生成失败: " + e.getMessage()
            );
        }
    }

    /**
     * 校验验证码
     */
    public static boolean checkCaptcha(String key, String inputCode) {
        // 添加调试信息
        System.out.println("验证码校验 - key: " + key + ", inputCode: " + inputCode);
        
        if (key == null || inputCode == null) {
            System.out.println("验证码校验失败：key或inputCode为null");
            return false;
        }

        String realCode = CAPTCHA_STORE.get(key);
        System.out.println("验证码校验 - realCode: " + realCode);
        
        if (realCode == null) {
            System.out.println("验证码校验失败：未找到对应的验证码");
            return false;
        }

        boolean result = inputCode.equalsIgnoreCase(realCode);
        System.out.println("验证码校验结果: " + result);
        
        // 验证一次后删除，防止重复使用
        CAPTCHA_STORE.remove(key);
        return result;
    }
}